<template>
  <div class="p-20px">
    <div v-show="alarms.length === 0" class="text-24px text-center text-gray-500"
      >未配置告警规则</div
    >
    <div v-show="alarms.length != 0">
      <AlarmForm
        v-for="item in alarms"
        :key="item.id"
        @delete="del"
        :data="item"
        @update="updateAlarm"
        :disable="isDisable"
      />
    </div>
    <Button type="primary" @click="addAlarm" v-show="!isDisable" class="my-24px"
      >添加告警规则</Button
    >
  </div>
</template>

<script lang="ts" setup>
  import { Button } from 'ant-design-vue';
  import { ref, watch, onMounted } from 'vue';
  import AlarmForm from './ALarmForm.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import _ from 'lodash';
  import { nanoid } from 'nanoid';
  let isDisable = ref<boolean>(false);
  const props = defineProps({
    formData: {
      type: Object,
    },
    disable: { type: Boolean },
  });
  let alarms = ref<any>([]);
  let alarm = ref<Recordable>({
    alarmType: '',
    id: '',
    propagate: false,
    clearRules: [],
    createRule: [],
    propagateRelationTypes: [],
    propagateToOwner: false,
    propagateToTenant: false,
  });
  const { createMessage } = useMessage();
  let emitsValue = ref<Recordable>();
  watch(
    () => props.formData,
    (nVal) => {
      emitsValue.value = nVal;
    },
    { immediate: true },
  );
  watch(
    () => props.disable,
    (nVal) => {
      isDisable.value = nVal;
    },
    { immediate: true },
  );
  onMounted(() => {
    if (emitsValue.value) {
      emitsValue.value.map((data) => {
        //处理clearRule
        if (data.clearRule) {
          if (data.clearRule.dashboardId) {
            data.clearRule.dashboardId = JSON.stringify(data.clearRule.dashboardId);
          }

          if (data.clearRule.schedule) {
            if (data.clearRule.schedule.type === 'SPECIFIC_TIME') {
              data.clearRule.schedule.startsOn = formatTime(data.clearRule.schedule.startsOn);
              data.clearRule.schedule.endsOn = formatTime(data.clearRule.schedule.endsOn);
            }
            if (data.clearRule.schedule.type === 'CUSTOM') {
              data.clearRule.schedule.items.map((time) => {
                if (time.enabled) {
                  time.endsOn = formatTime(time.endsOn);
                  time.startsOn = formatTime(time.startsOn);
                }
              });
            }
          } else {
            data.clearRule.schedule = {
              type: 'ANY_TIME',
            };
          }
          let keyArray: Array<any> = [];
          // 一个二维数组，把key的值完全相同的condition放在一个数组里
          let array: Array<any> = [];
          data.clearRule.condition.condition.map((item) => {
            let keyObj = { key: item.key.key, type: item.key.type, valueType: item.valueType };
            let index = keyArray.findIndex((obj) => JSON.stringify(obj) === JSON.stringify(keyObj));
            if (index < 0) {
              keyArray.push(keyObj);
              index = keyArray.length - 1;
              array.push([_.cloneDeep(item)]);
            } else {
              array[index].push(_.cloneDeep(item));
            }
          });
          data.clearRule.condition.condition = array;
          data.clearRules = [];
          data.clearRules.push(_.cloneDeep(data.clearRule));
          delete data.clearRule;
        } else {
          data.clearRules = [];
        }
        data.createRule = [];
        //处理createRules
        if (data.createRules) {
          for (let key of Object.keys(data.createRules)) {
            data.createRules[key].Severity = key;
            data.createRule.push(_.cloneDeep(data.createRules[key]));
          }
        }
        data.createRule.map((rule) => {
          if (rule.dashboardId) {
            rule.dashboardId = JSON.stringify(rule.dashboardId);
          }
          if (rule.schedule) {
            if (rule.schedule.type === 'SPECIFIC_TIME') {
              rule.schedule.startsOn = formatTime(rule.schedule.startsOn);
              rule.schedule.endsOn = formatTime(rule.schedule.endsOn);
            }
            if (rule.schedule.type === 'CUSTOM') {
              rule.schedule.items.map((item) => {
                if (item.enabled) {
                  item.endsOn = formatTime(item.endsOn);
                  item.startsOn = formatTime(item.startsOn);
                }
              });
            }
          } else {
            rule.schedule = { type: 'ANY_TIME' };
          }

          let keyArray: Array<any> = [];
          // 一个二维数组，把key的值完全相同的condition放在一个数组里
          let array: Array<any> = [];
          rule.condition.condition.map((item) => {
            let keyObj: any = { key: item.key.key, type: item.key.type, valueType: item.valueType };
            let index = keyArray.findIndex((obj) => JSON.stringify(obj) === JSON.stringify(keyObj));
            if (index < 0) {
              keyArray.push(keyObj);
              index = keyArray.length - 1;
              array.push([_.cloneDeep(item)]);
            } else {
              array[index].push(_.cloneDeep(item));
            }
          });
          rule.condition.condition = _.cloneDeep(array);
        });
      });
      alarms.value = _.cloneDeep(emitsValue.value);
    }
  });
  function formatTime(time: number) {
    let totalSeconds = time / 1000;
    let hours = Math.floor(totalSeconds / 3600);
    let minutes = Math.floor((totalSeconds % 3600) / 60);
    let seconds = Math.floor(totalSeconds % 60);
    // 格式化输出为两位数
    hours = parseInt(String(hours).padStart(2, '0'));
    minutes = parseInt(String(minutes).padStart(2, '0'));
    seconds = parseInt(String(seconds).padStart(2, '0'));
    return hours + ':' + minutes + ':' + seconds;
  }
  //删除
  function del(data: Recordable) {
    alarms.value = alarms.value.filter((item) => item.id != data.id);
  }
  //添加
  function addAlarm() {
    alarm.value.id = '';
    alarm.value.id = nanoid();
    alarms.value.push(_.cloneDeep(alarm.value));
  }
  function updateAlarm(data: Recordable) {
    alarms.value.map((item) => {
      if (item.id === data.id) {
        item = data;
      }
    });
  }
  function getAlarmsData() {
    let hasEmpty = false;
    alarms.value.map((item) => {
      let rulesData: any = {};
      item.CRule = [];
      let data: any = {};
      if (!item.alarmType) {
        createMessage.error('告警类型不能为空');
        hasEmpty = true;
        return;
      }

      if (!item.createRule.length) {
        createMessage.error('创建告警规则不能为空');
        hasEmpty = true;
        return;
      }
      item.createRule.map((rule) => {
        if (!rule.condition) {
          createMessage.error('创建告警规则条件不能为空');
          hasEmpty = true;
          return;
        }
        if (rule.dashboardId) {
          rule.dashboardId = JSON.parse(rule.dashboardId);
        }
        let param: Array<any> = [];
        data = _.cloneDeep(rule);
        rule.condition.condition.map((cond) => {
          cond.map((item) => {
            param.push(item);
          });
        });
        data.condition.condition = param;
        item.CRule.push(data);
      });

      item.CRule.map((rule) => {
        if (!rule.schedule) {
          createMessage.error('创建告警启用规则不能为空');
          hasEmpty = true;
          return;
        }
        if (!rule.Severity) {
          createMessage.error('创建告警严重程度不能为空');
          hasEmpty = true;
          return;
        }
        if (rule.schedule.type === 'SPECIFIC_TIME') {
          let arrayStart = rule.schedule.startsOn.split(':');
          rule.schedule.startsOn =
            (Number(arrayStart[0]) * 3600 + Number(arrayStart[1]) * 60 + Number(arrayStart[2])) *
            1000;
          let arrayEnd = rule.schedule.endsOn.split(':');
          rule.schedule.endsOn =
            (Number(arrayEnd[0]) * 3600 + Number(arrayEnd[1]) * 60 + Number(arrayEnd[2])) * 1000;
        }
        if (rule.schedule.type === 'CUSTOM') {
          rule.schedule.items.map((time) => {
            if (time.enabled) {
              let arrayStart = time.startsOn.split(':');
              time.startsOn =
                (Number(arrayStart[0]) * 3600 +
                  Number(arrayStart[1]) * 60 +
                  Number(arrayStart[2])) *
                1000;
              let arrayEnd = time.endsOn.split(':');
              time.endsOn =
                (Number(arrayEnd[0]) * 3600 + Number(arrayEnd[1]) * 60 + Number(arrayEnd[2])) *
                1000;
            }
          });
        }
        if (rule.Severity === 'CRITICAL') {
          rulesData.CRITICAL = rule;
        } else if (rule.Severity === 'MAJOR') {
          rulesData.MAJOR = rule;
        } else if (rule.Severity === 'MINOR') {
          rulesData.MINOR = rule;
        } else if (rule.Severity === 'WARNING') {
          rulesData.WARNING = rule;
        } else if (rule.Severity === 'INDETERMINATE') {
          rulesData.INDETERMINATE = rule;
        }
      });
      item.createRules = rulesData;
      // delete item.createRule;
      delete item.CRule;
      rulesData = {};
      if (item?.clearRules?.length > 0) {
        let data = _.cloneDeep(item.clearRules[0]);
        let param: Array<any> = [];
        if (!data.condition) {
          createMessage.error('清除告警规则条件不能为空');
          hasEmpty = true;
        }
        if (data.dashboardId) {
          data.dashboardId = JSON.parse(data.dashboardId);
        }
        data.condition.condition.map((cond) => {
          cond.map((item) => {
            param.push(item);
          });
        });
        data.condition.condition = param;
        if (!data.schedule) {
          createMessage.error('清除告警启用规则不能为空');
          hasEmpty = true;
          return;
        }
        if (data.schedule.type === 'SPECIFIC_TIME') {
          let arrayStart = data.schedule.startsOn.split(':');
          data.schedule.startsOn =
            (Number(arrayStart[0]) * 3600 + Number(arrayStart[1]) * 60 + Number(arrayStart[2])) *
            1000;
          let arrayEnd = data.schedule.endsOn.split(':');
          data.schedule.endsOn =
            (Number(arrayEnd[0]) * 3600 + Number(arrayEnd[1]) * 60 + Number(arrayEnd[2])) * 1000;
        }
        if (data.schedule.type === 'CUSTOM') {
          data.schedule.items.map((time) => {
            if (time.enabled) {
              let arrayStart = time.startsOn.split(':');
              time.startsOn =
                (Number(arrayStart[0]) * 3600 +
                  Number(arrayStart[1]) * 60 +
                  Number(arrayStart[2])) *
                1000;
              let arrayEnd = time.endsOn.split(':');
              time.endsOn =
                (Number(arrayEnd[0]) * 3600 + Number(arrayEnd[1]) * 60 + Number(arrayEnd[2])) *
                1000;
            }
          });
        }
        item.clearRule = data;
      }
    });

    if (hasEmpty) {
      return;
    }
    return alarms.value;
  }
  defineExpose({
    getAlarmsData,
  });
</script>
